using DocumentCreationSystem.Models.Memory;
using Microsoft.Extensions.Logging;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 增强的Agent记忆服务接口
    /// </summary>
    public interface IEnhancedAgentMemoryService
    {
        /// <summary>
        /// 存储记忆
        /// </summary>
        Task StoreMemoryAsync(string agentId, string content, string type = "general");

        /// <summary>
        /// 检索相关记忆
        /// </summary>
        Task<List<AgentMemoryItem>> RetrieveRelevantMemoriesAsync(string agentId, string query, int maxResults = 10);

        /// <summary>
        /// 获取记忆统计
        /// </summary>
        Task<int> GetMemoryCountAsync(string agentId);
    }

    /// <summary>
    /// 增强的Agent记忆服务实现
    /// </summary>
    public class EnhancedAgentMemoryService : IEnhancedAgentMemoryService
    {
        private readonly ILogger<EnhancedAgentMemoryService> _logger;
        private readonly Dictionary<string, List<AgentMemoryItem>> _memories = new();

        public EnhancedAgentMemoryService(ILogger<EnhancedAgentMemoryService> logger)
        {
            _logger = logger;
        }

        public async Task StoreMemoryAsync(string agentId, string content, string type = "general")
        {
            try
            {
                if (!_memories.ContainsKey(agentId))
                {
                    _memories[agentId] = new List<AgentMemoryItem>();
                }

                var memory = new AgentMemoryItem
                {
                    Id = Guid.NewGuid().ToString(),
                    AgentId = agentId,
                    Content = content,
                    Type = type,
                    CreatedAt = DateTime.Now,
                    LastAccessedAt = DateTime.Now,
                    AccessCount = 0,
                    Strength = 1.0,
                    Tags = new List<string>(),
                    Summary = content.Length > 100 ? content.Substring(0, 100) + "..." : content
                };

                _memories[agentId].Add(memory);
                _logger.LogInformation($"为Agent {agentId} 存储了新记忆: {type}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"存储记忆失败: Agent {agentId}");
                throw;
            }
        }

        public async Task<List<AgentMemoryItem>> RetrieveRelevantMemoriesAsync(string agentId, string query, int maxResults = 10)
        {
            try
            {
                if (!_memories.TryGetValue(agentId, out var agentMemories))
                {
                    return new List<AgentMemoryItem>();
                }

                // 简化的相关性匹配
                var relevantMemories = agentMemories
                    .Where(m => m.Content.Contains(query, StringComparison.OrdinalIgnoreCase) ||
                               m.Summary.Contains(query, StringComparison.OrdinalIgnoreCase))
                    .OrderByDescending(m => m.Strength)
                    .Take(maxResults)
                    .ToList();

                // 更新访问信息
                foreach (var memory in relevantMemories)
                {
                    memory.LastAccessedAt = DateTime.Now;
                    memory.AccessCount++;
                }

                _logger.LogInformation($"为Agent {agentId} 检索到 {relevantMemories.Count} 个相关记忆");
                return relevantMemories;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"检索记忆失败: Agent {agentId}");
                return new List<AgentMemoryItem>();
            }
        }

        public async Task<int> GetMemoryCountAsync(string agentId)
        {
            try
            {
                if (_memories.TryGetValue(agentId, out var agentMemories))
                {
                    return agentMemories.Count;
                }
                return 0;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取记忆数量失败: Agent {agentId}");
                return 0;
            }
        }
    }
}
